from datetime import timedelta

from odoo import api, fields, models, _
from odoo.tools import html2plaintext


class AgriDetectionSession(models.Model):
    _name = 'agri.detection.session'
    _description = 'AI 识别记录'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'detection_time desc'

    name = fields.Char(string='编号', required=True, copy=False, default='新建')
    detection_time = fields.Datetime(string='识别时间', default=lambda self: fields.Datetime.now(), tracking=True)
    partner_id = fields.Many2one('res.partner', string='农户/用户', tracking=True)
    handled_by = fields.Many2one('res.users', string='技术员', tracking=True, default=lambda self: self.env.user)
    crop_id = fields.Many2one('agri.crop', string='作物', tracking=True)
    disease_id = fields.Many2one('agri.disease', string='疑似病害', tracking=True)
    disease_confidence = fields.Float(string='病害置信度 (%)')
    pest_id = fields.Many2one('agri.pest', string='疑似虫害', tracking=True)
    pest_confidence = fields.Float(string='虫害置信度 (%)')
    detected_labels = fields.Char(string='原始标签', help='模型原始输出，用逗号分隔')
    advisory = fields.Html(string='处理建议', sanitize=False)
    audio_script = fields.Text(string='语音播报文案')
    image_1920 = fields.Image(string='现场照片', max_width=1920, max_height=1920)
    location_lat = fields.Float(string='纬度')
    location_lng = fields.Float(string='经度')
    location_accuracy = fields.Float(string='定位精度 (m)')
    location_text = fields.Char(string='位置描述')
    model_name = fields.Char(string='模型名称')
    model_version = fields.Char(string='模型版本')
    source = fields.Selection(
        selection=[
            ('android_offline', 'Android(离线)'),
            ('android_online', 'Android(连网)'),
            ('odoo', 'Odoo后台'),
            ('api', '外部API'),
        ],
        string='来源',
        default='android_online',
        tracking=True,
    )
    state = fields.Selection(
        selection=[
            ('draft', '待确认'),
            ('adviced', '已建议'),
            ('followup', '待复查'),
            ('resolved', '已解决'),
        ],
        default='draft',
        string='状态',
        tracking=True,
    )
    followup_date = fields.Date(string='复查日期', tracking=True)
    dataset_entry_ids = fields.One2many('agri.dataset.entry', 'detection_id', string='数据条目')

    DEFAULT_FOLLOWUP_DAYS = 3

    _sql_constraints = [
        ('detection_name_unique', 'unique(name)', '识别记录编号必须唯一。'),
    ]

    @api.model
    def create(self, vals):
        if vals.get('name', '新建') == '新建':
            vals['name'] = self.env['ir.sequence'].next_by_code('agri.detection.session') or '新建'
        return super().create(vals)

    def action_generate_advisory(self):
        for record in self:
            sections = []
            audio_lines = []
            if record.crop_id:
                audio_lines.append(_('作物：%s') % record.crop_id.display_name)

            if record.disease_id:
                disease = record.disease_id
                severity_label = dict(disease._fields['severity'].selection).get(disease.severity, disease.severity)
                sections.append(f"<h3>疑似病害：{disease.name}</h3>")
                sections.append(f"<p>危害等级：{severity_label}</p>")
                if disease.symptoms:
                    sections.append(f"<p><strong>症状：</strong>{disease.symptoms}</p>")
                if disease.treatment:
                    sections.append(f"<p><strong>处理：</strong>{disease.treatment}</p>")
                if disease.prevention:
                    sections.append(f"<p><strong>预防：</strong>{disease.prevention}</p>")
                if disease.recommended_products:
                    sections.append(f"<p><strong>推荐药剂：</strong>{disease.recommended_products}</p>")
                if disease.monitoring_tips:
                    sections.append(f"<p><strong>巡查要点：</strong>{disease.monitoring_tips}</p>")
                audio_lines.append(
                    (_('疑似病害 %(name)s，危害等级 %(level)s') % {'name': disease.name, 'level': severity_label})
                )
                if disease.treatment:
                    audio_lines.append(
                        _('建议处理：%s') % html2plaintext(disease.treatment or '').strip()
                    )

            if record.pest_id:
                pest = record.pest_id
                sections.append(f"<h3>疑似虫害：{pest.name}</h3>")
                if pest.symptoms:
                    sections.append(f"<p><strong>危害表现：</strong>{pest.symptoms}</p>")
                if pest.treatment:
                    sections.append(f"<p><strong>应急处理：</strong>{pest.treatment}</p>")
                if pest.prevention:
                    sections.append(f"<p><strong>综合防控：</strong>{pest.prevention}</p>")
                if pest.recommended_products:
                    sections.append(f"<p><strong>推荐药剂：</strong>{pest.recommended_products}</p>")
                if pest.monitoring_tips:
                    sections.append(f"<p><strong>巡查要点：</strong>{pest.monitoring_tips}</p>")
                audio_lines.append(_('疑似虫害 %(name)s') % {'name': pest.name})
                if pest.treatment:
                    audio_lines.append(_('应急处理建议：%s') % html2plaintext(pest.treatment or '').strip())

            if not sections:
                sections.append(_('<p>暂未匹配到知识库信息，请人工检查。</p>'))
                audio_lines.append(_('暂未匹配到知识库信息，请人工检查。'))

            record.advisory = ''.join(sections)
            script = '。'.join(filter(None, audio_lines)).strip('。')
            record.audio_script = f"{script}。" if script else False
            record.state = 'adviced'

            if not record.followup_date and record.env.context.get('agri_auto_followup', True):
                record.followup_date = fields.Date.today() + timedelta(days=record.DEFAULT_FOLLOWUP_DAYS)
                record._schedule_followup_activity()

        return True

    def action_mark_followup(self):
        for record in self:
            record.state = 'followup'
            if not record.followup_date:
                record.followup_date = fields.Date.today() + timedelta(days=record.DEFAULT_FOLLOWUP_DAYS)
            record._schedule_followup_activity()
        return True

    def action_mark_resolved(self):
        for record in self:
            record.state = 'resolved'
            todo_type = self.env.ref('mail.mail_activity_data_todo', raise_if_not_found=False)
            if todo_type:
                record.activity_ids.filtered(lambda act: act.activity_type_id == todo_type).unlink()
        return True

    def action_reset_to_draft(self):
        self.write({'state': 'draft'})
        return True

    def _schedule_followup_activity(self):
        Activity = self.env['mail.activity'].sudo()
        todo_type = self.env.ref('mail.mail_activity_data_todo', raise_if_not_found=False)
        if not todo_type:
            return
        for record in self:
            deadline = record.followup_date or fields.Date.today()
            user_id = record.handled_by.id or self.env.user.id
            record.activity_ids.filtered(lambda act: act.activity_type_id == todo_type and act.user_id.id == user_id).unlink()
            Activity.create({
                'res_id': record.id,
                'res_model_id': self.env['ir.model']._get_id(self._name),
                'activity_type_id': todo_type.id,
                'user_id': user_id,
                'summary': _('复查识别记录 %s') % record.name,
                'note': record.advisory or '',
                'date_deadline': deadline,
            })

